'use strict';

const Controller = require('../base.js');
const SELECT = require('../../../../config/select');

class BannerController extends Controller {
    /**
     *列表
     */
    async find() {
        const { ctx } = this;
        const { title, page, state, sort, currentPage, type } = ctx.query;
        const select = SELECT.BANNER;
        const res = await ctx.service.banner.find({ title, state, sort, page, currentPage, type }, select);
        ctx.success(res);
    }

    /**
     * 新增
     */
    async create() {
        const { ctx } = this;
        const body = ctx.request.body;
        const { title, desc, href, img, state, type } = body;
        const Rules = {
            title: {
                type: 'string',
                keyname: '广告标题'
            },
            desc: {
                type: 'string',
                keyname: '广告描述'
            }
        };
        ctx.proving(Rules);

        const res = await ctx.service.banner.create({ title, desc, href, img, state, type });
        ctx.success(res);
    }

    /**
     * 修改
     */
    async update() {
        const { ctx } = this;
        const body = ctx.request.body;
        const { id, title, desc, href, img, state,type } = body;
        const Rules = {
            title: {
                type: 'string',
                keyname: '广告标题'
            },
            desc: {
                type: 'string',
                keyname: '广告内容'
            }
        };
        ctx.proving(Rules);

        const res = await ctx.service.banner.update(id, { title, desc, href, img, state,type });
        ctx.success(res);
    }

    /**
     * 上架/下架
     * 0 下架 1 上架
     */
    async updateState() {
        const { ctx } = this;
        const body = ctx.request.body;
        const { id, state } = body;
        const res = await ctx.service.banner.update(id, { state });
        ctx.success(res);
    }

    /*
     * 删除
     * */
    async destroy() {
        const { ctx } = this;
        const query = ctx.query;
        const { id } = query.id;

        try {
            await ctx.service.banner.destroy(id);
            ctx.success({
                message: '删除成功'
            });
        } catch (e) {
            console.log(e)
            ctx.throw('402', '删除失败')
        }

    }
}

module.exports = BannerController;
